import re
from django_redis import get_redis_connection
from rest_framework import serializers

# 用户的序列化器
from tensquare.apps.users.models import User


class UserSeralizers(serializers.ModelSerializer):
    sms_code = serializers.CharField(label='短信验证码',write_only=True)
    token = serializers.CharField(label='token',read_only=True)
    class Meta:
        model = User
        fields = ('id','username','password','sms_code','mobile','token','avatar')
        extra_kwargs={'username':{'min_length':5,'max_length':20,'error_messages':{'min_length':'仅允许５－２０个字符的用户名','max_length':'仅允许５－２０个字符的用户名'}},
                      'password':{'write_only':True,'min_length':8,'max_length':20,'error_messages':{'min_length':'仅允许８－２０个字符的密码','max_length':'仅允许８－２０个字符的密码'}}}

    # 判断短信验证吗
    def validate(self, data):
        redis = get_redis_connection('verify_codes')
        mobile = data['mobile']
        real_sms_code = redis.get('sms_%s'%mobile)
        if real_sms_code is None:
            raise serializers.ValidationError('无效的短信验证码')
        if data['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return  data

    # 验证手机号
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value